import { createProxyMiddleware, Options } from 'http-proxy-middleware';
import { HttpsProxyAgent } from 'https-proxy-agent';
import { configs } from '../../src/config';
const pathRewriteRegEx = `^${configs.apiPrefix}`;
const routerRegEx = `/${configs.apiPrefix}`; // path only

// const agent = process.env.APP_ENV === 'localhost' && {
//   secure: false,
//   agent: new HttpsProxyAgent('http://168.219.61.252:8080'),
// };

const agent = process.env.APP_ENV === 'localhost111' && {
  secure: false,
  agent: new HttpsProxyAgent('http://168.219.61.252:8080'),
};

// proxy middleware options
const options: Options = {
  ...agent, // in Suwon proxy
  target: configs.apiServer, // target host
  changeOrigin: true, // needed for virtual hosted sites
  pathRewrite: {
    [pathRewriteRegEx]: '/', // rewrite path: /api/data --> /
  },
  router: {
    // when request.headers.host == 'localhost:3000',
    // override target host to '{configs.apiServer}}'
    [routerRegEx]: configs.apiServer,
  },
  onError: (err, req, res) => {
    console.error(err);
    // return 502 Bad Gateway
    res.status(502).json({
      reason: err.message,
    });
  },
};

export default createProxyMiddleware(options);
